package com.tuling.jucdemo.jmm;
/**
 * CAS测试之 自旋CAS长时间地不成功，则会给 CPU 带来非常大的开销
 */

import com.tuling.jucdemo.lock.CASLock;
import java.util.concurrent.locks.ReentrantLock;

public class Test {
    private volatile static int sum = 0;
    private static Object object = new Object();
    private static ReentrantLock lock = new ReentrantLock();
    private static CASLock casLock = new CASLock();

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //synchronized (object) { // synchronized会消耗大量资源  线程会切换到内核态调用park()方法 会有性能问题
                    //lock.lock();
                    for(;;){
                        //state == 0
                        if(casLock.getState() == 0 && casLock.cas()){
                            try {
                                for (int j = 0; j < 10000; j++) {
                                    sum++;
                                    // }
                                }
                                System.out.println(casLock.getState());
                            } finally{
                                //lock.unlock();
                                //state = 0
                                casLock.setState(0);
                            }
                            break;
                        }
                    }
                }
            }).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sum=" + sum);
    }
}

